<template>
  <BasicSearch ref="basicSearch" :formItemList="formItemList" @handleSearch="handleSearch" @handleReset="handleReset">
    <template #btnOptions>
      <el-button type="primary" plain :icon="Plus" v-has-permission="'job:manage:add'" @click="add">新增</el-button>
      <el-button type="primary" plain :icon="Edit" v-has-permission="'job:manage:edit'" @click="edit">修改</el-button>
      <el-button type="primary" plain :icon="View" v-has-permission="'job:manage:detail'" @click="detail">查看</el-button>
      <el-button type="primary" plain :icon="Delete" v-has-permission="'job:manage:del'" @click="del">删除</el-button>
      <el-button type="primary" plain :icon="Delete" v-has-permission="'job:manage:changeStatus'" @click="changeStatus('0')">启用</el-button>
      <el-button type="primary" plain :icon="Delete" v-has-permission="'job:manage:changeStatus'" @click="changeStatus('1')">停用</el-button>
      <el-button type="primary" plain :icon="Delete" v-has-permission="'job:manage:run'" @click="run">立即执行</el-button>
    </template>
  </BasicSearch>

  <STable ref="sTable" :dataSource="dataSource.tableData" :columns="columns" :total="dataSource.total"
    :loading="dataSource.loading" :tableProps="dataSource.tableProps" @onPageChange="handlePageChange"
    @handleSelection="handleSelectRows">
    <template #status="{ row, index }">
      {{ row.status ==='0' ? '启用' : '停用' }}
    </template>
    <template #sysJobOnce="{ row, index }">
      {{ row.sysJobOnce === '1'? '一次性任务' : '持续性任务'}}
    </template>
    <template #finish="{ row, index }">
      {{ row.finish === '1'? '完成' : '未完成'}}
    </template>
  </STable>

  <JobManageAlert v-if="isAlert" :isAlert="isAlert" :flag="alertFlag" :info="currInfo" @closeDialog="closeDialog">
  </JobManageAlert>
  
</template>
<script lang="ts" setup>
import {Plus,Edit,View,Delete} from '@element-plus/icons-vue'
import { DataType, ColumnsType } from "@components/common/Table/tableTypes";
import { UseFormItem, OptionsData } from "@components/common/BasicSearch/serchTypes";
import { alertEditAndLook, removeData,} from "@/utils";
import { commonStateEnum } from "@/utils/staticData";
import JobManageAlert from "./components/JobManageAlert.vue";
import { jobManageQuery, jobManageDel, jobManageChangeStatus, jobManageRun } from "@/request/apis/job/jobManage";

/************************表格相关**********************/
let columns = ref<Array<ColumnsType>>([
  { title: "多选", type: 'selection', width: 65 },
  { title: "序号", type: "index", width: 120 },
  { title: "任务名称", key: "jobName" },
  { title: "任务组名", key: "jobGroup" },
  { title: "任务类全名", key: "jobClassName" },
  { title: "cron执行表达式", key: "cronExpression" },
  { title: "任务状态", key: "status", slot: "status" },
  { title: "是否一次性", key: "sysJobOnce", slot: "sysJobOnce" },
  { title: "完成状态", key: "finish", slot: "finish" },
]);

// 表格参数
let dataSource = reactive({
  tableData: [] as Array<DataType>,
  loading: false,
  total: 0,
  tableProps: {
    "row-key": "id",
  },
});
const selectionsRows = ref<Array<DataType>>([]);
// 获取选中的载体
function handleSelectRows(selection: Array<DataType>) {
  selectionsRows.value = selection;
}

// 切换分页
function handlePageChange() {
  getData();
}

// 获取数据
function getData() {
  dataSource.loading = true;
  let params = {
    currentPage: sTable.value.current,
    pageSize: sTable.value.pageSize,
    ...basicSearch.value.searchInfo
  };
  jobManageQuery(params)
    .then((res: Response) => {
      dataSource.tableData = res.data;
      dataSource.loading = false;
      dataSource.total = res.totalRecords;
    })
    .catch((err) => {
      dataSource.loading = false;
    });
}

// ---------------操作---------------
//#region
let isAlert = ref<boolean>(false);
const alertFlag = ref("");

let currInfo = reactive<object>({})

provide("handleCancel", closeDialog);
// 关闭弹框
function closeDialog(flag: number) {
  isAlert.value = false;
  if (flag == 1) {
    getData();
  }
}

// 删除数据
function delData() {
  let ids: any[] = []
  selectionsRows.value.map(item => {
    ids.push(item.jobId)
  })
  jobManageDel(ids).then(res => {
    getData();
    ElMessage.success('删除成功')
  }).catch(err => {

  })
}

//新增操作
function add(){
  alertFlag.value = 'job_add';
  isAlert.value = true;
}

//修改操作
function edit(){
  alertFlag.value = 'job_edit';
  if (alertEditAndLook(selectionsRows.value)) {
    currInfo = selectionsRows.value[0]
    isAlert.value = true;
  }
}

//查看操作
function detail(){
  alertFlag.value = 'job_look';
  if (alertEditAndLook(selectionsRows.value)) {
    currInfo = selectionsRows.value[0]
    isAlert.value = true;
  }
}
//删除按钮操作
function del(){  
  removeData(selectionsRows.value, delData)
}
//修改状态
function changeStatus(status:string){
    if (alertEditAndLook(selectionsRows.value)) {
        const params = {
            jobId : selectionsRows.value[0].jobId,
            status : status
        }
        jobManageChangeStatus(params).then(res => {
            getData();
            ElMessage.success('状态修改成功')
        }).catch(err => {

        })
    }
}


function run(status:string){
    if (alertEditAndLook(selectionsRows.value)) {
        jobManageRun(selectionsRows.value[0].jobId).then(res => {
            ElMessage.success('已发送执行命令')
        }).catch(err => {

        })
    }
}
//#endregion

/************************* 查询相关 **************************/
//#region
const sTable = ref();
const basicSearch = ref();

// 搜索条件
let formItemList = ref<Array<UseFormItem>>([
  { type: "input", label: "任务名称", prop: "jobName" },
  { type: "input", label: "任务组", prop: "jobGroup" },
]);

// 查询
function handleSearch() {
  sTable.value.setCurrentPage(1);
  sTable.value.setPageSize(10);
  getData();
}

// 重置
function handleReset() {
  sTable.value.setCurrentPage(1);
  sTable.value.setPageSize(10);
  getData();
}
//#endregion

// 初始化
onMounted(() => {
  getData();
});
</script>

<style scoped lang="scss">
.table_opt {
  margin-bottom: 10px;
}
</style>